package com.cyf.filmDownload.common.util;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class FileUtil {

    public static File createFile(String filePath) {
        Path path = Paths.get(filePath);
        try {
            Files.createDirectories(path.getParent());
            // 如果文件不存在，则创建；如果存在，则打开并清空内容
            Files.write(path, new byte[0], StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return path.toFile();
    }

    public static void createDir(String dir) {
        try {
            Files.createDirectories(Paths.get(dir));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeLinesToFile(String filePath, List<String> lines) {
        File file = createFile(filePath);
        try {
            FileUtils.writeLines(file, lines);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static void writeBytesToFile(String filePath, byte[] bytes) {
        File file = createFile(filePath);
        try {
            FileUtils.writeByteArrayToFile(file, bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
